package com.levy.controller;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.levy.common.CommonResult;
import com.levy.entity.User;
import com.levy.service.UserService;

/**
 * 登录控制器
 *
 * @author liwei515
 */
@RestController
public class LoginController {

  @Autowired
  private UserService userService;

  /**
   * 负责处理/请求
   *
   * @return index页面
   */
  @GetMapping("/")
  public CommonResult<?> index() {
    return CommonResult.success();
  }

  /**
   * 负责处理/loginCheck的请求
   *
   * @param request 请求
   * @return ModelAndView
   */
  @RequestMapping("/loginCheck/{userName}/{password}")
  public CommonResult<?> loginCheck(HttpServletRequest request, @PathVariable String userName, @PathVariable String password) {
    boolean isValidUser = userService.hasMatchUser(userName, password);
    if (!isValidUser) {
      return CommonResult.error(404, "用户名或密码错误");
    } else {
      User user = userService.findUserByUserName(userName);
      user.setLastVisit(new Date());
      user.setLastIp(request.getLocalAddr());
      userService.loginSuccess(user);
      request.getSession().setAttribute("user", user);
      return CommonResult.success(user);
    }
  }

}
